package com.jar.exercise.多线程.线程池;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhangShengHao
 * @className Demo
 * @description TODO
 * @date 2020/3/5 14:35
 */
public class Demo {
	@Test
	public void newCachedThreadPool() {
		ExecutorService service = Executors.newCachedThreadPool();
		for (int i = 0; i < 7; i++) {
			final int index = i;
				service.execute(()->{
					try {
						System.out.println("时间是:" + System.currentTimeMillis() + "第" + index + "个线程" + Thread.currentThread().getName());
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				});
		}
	}

	@Test
	public void newFixedThreadPool() {
		// TODO Auto-generated method stub
		//设置最大线程数5个
		ExecutorService mFixedThreadPool = Executors.newFixedThreadPool(5);

		for (int i = 0; i < 7; i++) {
			final int index = i;
			mFixedThreadPool.execute(() -> {
				try {
					System.out.println("时间是:" + System.currentTimeMillis() + "第" + index + "个线程" + Thread.currentThread().getName());
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
		}
	}

	@Test
	public void newScheduledThreadPool() {
		//设置最大线程数5个
		//设置池中核心数量是2
		ScheduledExecutorService mScheduledThreadPool = Executors.newScheduledThreadPool(2);
		System.out.println("现在的时间:" + System.currentTimeMillis());
		mScheduledThreadPool.schedule(() -> {
			// TODO Auto-generated method stub
			System.out.println("现在的时间:" + System.currentTimeMillis());

		}, 4, TimeUnit.SECONDS);//这里设置延迟4秒执行
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//设置池中核心数量是2
		ScheduledExecutorService mScheduledThreadPool = Executors.newScheduledThreadPool(2);
		System.out.println("现在的时间:" + System.currentTimeMillis());
		mScheduledThreadPool.scheduleAtFixedRate(() -> {
			// TODO Auto-generated method stub
			System.out.println(Thread.currentThread().getName() + "现在的时间:" + System.currentTimeMillis());

		}, 2, 3, TimeUnit.SECONDS);//这里设置延迟2秒后每3秒执行一次

	}
}
